package com.liu;

import com.liu.servlet.LiuServlet;
import com.liu.servlet.Request;
import com.liu.servlet.Response;

import javax.servlet.ServletException;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * @author LIU
 * @version 1.0
 * @description TODO
 * @date 2024/2/5 17:35
 */
public class SocketProcessor implements Runnable {

    private Socket socket;

    public SocketProcessor(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
//          System.out.println(socket);
            byte[] bytes = new byte[1024];
            socket.getInputStream().read(bytes);

            for (byte b : bytes) {
                System.out.print((char) b);
            }
            System.out.println();
            System.out.println("======================");


            Request request = parseRequest(bytes);
            Response response = new Response(request);
            LiuServlet liuServlet = new LiuServlet();
            liuServlet.service(request,response);

            // 响应数据
            response.complete();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }

    /**
     *  解析请求方式、uri、请求协议
     */
    private Request parseRequest(byte[] bytes) {
        int pos = 0, begin = 0, end = 0;
        for (; pos < bytes.length; pos++, end++) {
            if (bytes[pos] == ' ') break;
        }
        StringBuilder method = new StringBuilder();
        for (; begin < end; begin++) {
            method.append((char) bytes[begin]);
        }

        pos ++;
        begin ++;
        end++;
        for (; pos < bytes.length; pos++, end++) {
            if (bytes[pos] == ' ') break;
        }
        StringBuilder uri = new StringBuilder();
        for (; begin < end; begin++) {
            uri.append((char) bytes[begin]);
        }

        pos ++;
        begin ++;
        end++;
        for (; pos < bytes.length; pos++, end++) {
            if (bytes[pos] == '\r') break;
        }
        StringBuilder protocol = new StringBuilder();
        for (; begin < end; begin++) {
            protocol.append((char) bytes[begin]);
        }


        Request request = new Request(method.toString(), uri.toString(), protocol.toString(),socket);
        return request;
    }
}
